package com.humble.humbleojjudgeservice.judge.rabbit;

import com.humble.humbleojcommon.common.ErrorCode;
import com.humble.humbleojcommon.exception.BusinessException;
import com.humble.humbleojjudgeservice.judge.JudgeService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class QuestionMessageConsumer {
    @Resource
    private JudgeService judgeService;


    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"humbleojQueue"}, ackMode = "MANUAL") //手动确认模式
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        long submitId = Long.parseLong(message);
        try {
            judgeService.doJudgeService(submitId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            //这里直接将消息截止了，可以选择进行重发
            channel.basicNack(deliveryTag, false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题服务出现异常");
        }
    }


}
